package com.puppy.controller;

import com.puppy.anno.Log;
import com.puppy.pojo.Dept;
import com.puppy.pojo.Result;
import com.puppy.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@SuppressWarnings("ALL")
@Slf4j
@RequestMapping("/depts")
//@Lazy //延迟创建bean，直到第一次使用时
@Scope("prototype") //多例bean，每次使用创建新的bean，线程安全
@RestController //默认bean是单例 - singleton :默认单例bean在项目启动时创建，并存入容器中，所有线程共享，线程不安全
public class DeptController {

    public DeptController() {
        System.out.println("DeptController创建了...");
    }

    //选择Slf4j日志的Logger/LoggerFactory
//    public static final Logger log = LoggerFactory.getLogger(DeptServiceImpl.class);
    @Autowired
    private DeptService deptService;

    //    @RequestMapping(value = "/depts",method = RequestMethod.GET)
    //@GetMapping("/depts")是RequestMapping的子集，里面定义了method=RequestMethod.GET
    @GetMapping
    @Log //自定义注解，记录日志,切入点方法
    public Result list() {
        List<Dept> depts = deptService.findAll();
        return Result.success(depts);
    }

    @DeleteMapping//前端url传递id参数，后端接收
    public Result delete(Integer id) {
        deptService.deleteById(id);
        return Result.success();
    }

    @PostMapping
    public Result add(@RequestBody Dept dept) {
        deptService.addByName(dept);
        System.out.println("新增部门：" + dept);
        return Result.success();
    }

    @Transactional
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.debug("debug...");
        log.info("根据id查询部门：" + id);
        Dept dept = deptService.getById(id);
        log.info("查询结果：{}", dept); //log.info("查询结果：{}",dept);{}是占位符，代表后面的参数
        log.debug("debug...");
        return Result.success(dept);
    }

    @PutMapping
    public Result update(@RequestBody Dept dept) {
        deptService.updateById(dept);
        return Result.success();
    }
}
